﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Anke.SHManage.Model;
using Anke.SHManage.BLL;
using Anke.SHManage.Utility;
using System.Data;
using System.Data.SqlClient;

namespace Anke.SHManage.Web.Areas.IM.Controllers
{
    public class I_DeliveryController : Controller
    {
        //
        // GET: /IM/I_Delivery/


        public ActionResult I_DeliveryList()
        {
            UserOperateContext userOperateContext = new UserOperateContext();
            bool Insert = userOperateContext.getGongneng(1312);////判断登录人有无财务审批权限 
            if (Insert)
            {
                this.ViewData["RolePermissionInsert"] = "Insert";//登录人有审批权限
            }
            else
            {
                this.ViewData["RolePermissionInsert"] = "";
            }

            this.ViewData["reMonth"] = new I_BalanceBLLExt().GetBalanceMaxReMonth();//取I_BalanceList表中最大的报表月份+1，赋给点击入账的月份
            return View();
        }

        public ActionResult DataLoad()
        {
            //统计时间
            DateTime StartDate = Convert.ToDateTime(Request.Form["StartDate"]); //查询起时间 单一参数
            DateTime EndDate = Convert.ToDateTime(Request.Form["EndDate"]); //查询止时间 单一参数
            string DeliveryCode = Request.Form["DeliveryCode"].ToString();//出库单号 单一参数
            string DeliveryType = Request.Form["DeliveryType"].ToString();  //出库类型 单一参数


            string SelectStorage = Request.Form["SelectStorage"].ToString(); //来源仓库编码
            List<int> listSourceStroageIDs = new List<int>();
            if (SelectStorage.Length > 0)
                listSourceStroageIDs.Add(int.Parse(SelectStorage));
            else
                listSourceStroageIDs = UserOperateContext.Current.Session_StorageRelated.listUserStorage;

            string TargetStorage = Request.Form["TargetStorage"].ToString(); //目标仓库编码
            List<int> listTargetStorageIDs = null;
            if (TargetStorage != "")
                listTargetStorageIDs = TargetStorage.Split(',').Select<string, int>(e => Convert.ToInt32(e)).ToList();

            string MaterialType = Request.Form["MaterialType"].ToString();
            List<string> mTypeList = UserOperateContext.Current.getMaterialTypeList(MaterialType);
            string MaterialID = Request.Form["MaterialID"].ToString();
            //2016-4-11 新增条件，是否审核
            string IFCheck = Request.Form["IFCheck"].ToString();


            //获取页容量
            int pageSize = int.Parse(Request.Form["rows"]);
            //获取请求的页码
            int pageIndex = int.Parse(Request.Form["page"]);
            int total = 0;
            var list = new I_DeliveryBLL().GetDeliveryList(pageIndex, pageSize, ref total, StartDate, EndDate, DeliveryCode, DeliveryType, listSourceStroageIDs,
                listTargetStorageIDs, mTypeList, MaterialID, IFCheck);
            return Json(new { total = total, rows = list }, "appliction/json", JsonRequestBehavior.AllowGet);
        }


        //2016-4-11 新增出库审核
        [HttpPost]
        public ActionResult SavaPickCheck()
        {

            string sDeliveryDetailInfo = Request.Form["sDeliveryDetailInfo"].ToString();
            List<I_DeliveryDetail> relist = JsonHelper.GetJsonInfoBy<List<I_DeliveryDetail>>(sDeliveryDetailInfo); //前台传来的从表数据
            string reportMonth = Request.Form["CheckMonth"].ToString();

            if (relist.Count > 0)
            {
                DateTime tempNow = DateTime.Now;
                int resulDeliveryDetail = relist.Count;
                int resultInventoryRecord = relist.Count;
                int resultInventoryEntryRecord = relist.Count;

                //循环将入库字表的IFcheck和CheckTime值改变
                for (int i = 0; i < relist.Count; i++)
                {
                    string tempDeliveryDetailCode = relist[i].DeliveryDetailCode;
                    //先根据EntryDetailCode 将实体取出来，看是否存在IFCHECK 和CheckTime 如果存在就不更改
                    I_DeliveryDetail DeliveryDetailinfo = new I_DeliveryDetailBLL().GetModelWithOutTrace(p => p.DeliveryDetailCode == tempDeliveryDetailCode);

                    if (DeliveryDetailinfo.IFCheck != true || DeliveryDetailinfo.IFCheck == null) //判断是否有I_EntryDetail 
                    {
                        DeliveryDetailinfo.IFCheck = true;
                        DeliveryDetailinfo.CheckTime = tempNow;
                        DeliveryDetailinfo.ReportMonth = reportMonth;

                        int resultDetail = new I_DeliveryDetailBLL().Modify(DeliveryDetailinfo, "IFCheck", "CheckTime", "ReportMonth");
                        resulDeliveryDetail = resulDeliveryDetail + resultDetail;


                    }
                    else
                    {
                        //return this.JsonResult(Utility.E_JsonResult.Error, "对不起，已审核过，无法重复审核！", null, null);
                    }
                    //把Record 中的DeliveryDetailCode 那一条取出来，再更改IFCheck，CheckTime
                    I_InventoryRecord inInfo = new I_InventoryRecordBLL().GetModelWithOutTrace(p => p.DeliveryDetailCode == tempDeliveryDetailCode);

                    if (inInfo.IFCheck != true || inInfo.IFCheck == null)  //判断是否有Record
                    {
                        inInfo.IFCheck = true;
                        inInfo.CheckTime = tempNow;
                        inInfo.ReportMonth = reportMonth;

                        int resultRecord = new I_InventoryRecordBLL().Modify(inInfo, "IFCheck", "CheckTime", "ReportMonth");
                        resultInventoryRecord = resultInventoryRecord + resultRecord;
                    }
                    else
                    {
                        //return Json("");
                    }
                    //判断如果为转库，出库已经审核情况下， 自动更改入库的审核
                    I_InventoryRecord inEntryInfo = new I_InventoryRecordBLL().GetModelWithOutTrace(p => p.EntryDetailCode == tempDeliveryDetailCode);

                    if (inEntryInfo.IFCheck != true || inEntryInfo.IFCheck == null)  //判断是否有Record
                    {
                        inEntryInfo.IFCheck = true;
                        inEntryInfo.CheckTime = tempNow;
                        inEntryInfo.ReportMonth = reportMonth;

                        int resultEntryRecord = new I_InventoryRecordBLL().Modify(inEntryInfo, "IFCheck", "CheckTime", "ReportMonth");
                        resultInventoryEntryRecord = resultInventoryEntryRecord + resultEntryRecord;
                    }
                    else
                    {
                        //return Json("");
                    }

                }
                if (resulDeliveryDetail >= relist.Count && resultInventoryRecord >= relist.Count && resultInventoryEntryRecord >= relist.Count)
                {
                    return this.JsonResult(Utility.E_JsonResult.OK, "入账成功！", null, null);
                }
                else
                {
                    return this.JsonResult(Utility.E_JsonResult.Error, "入账失败！", null, null);
                }
            }
            else
            {
                return Json("");
            }

        }






        public ActionResult I_DeliveryDetail()
        {
            return View();
        }

        /// <summary>
        /// 记录出库信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveDeliveryDetail()
        {
            string ConsigneeID = Request.Form["ConsigneeID"].ToString();
            DateTime DeliveryDate = Convert.ToDateTime(Request.Form["DeliveryDate"]);
            int ReceivingStoreID = int.Parse(Request.Form["ReceivingStoreID"]);
            string Remark = Request.Form["Remark"].ToString();
            string sDeliveryDetailInfo = Request.Form["sDeliveryDetailInfo"].ToString();
            string AmbulanceCode = Request.Form["AmbulanceCode"].ToString();//20151126--增加车辆编码
            List<I_DeliveryDetail> relist = JsonHelper.GetJsonInfoBy<List<I_DeliveryDetail>>(sDeliveryDetailInfo);
            I_Delivery delivery = new I_Delivery();

            //2018-12-11 zch
            //delivery.DeliveryCode = DateTime.Now.AddSeconds(1).ToString("yyyyMMddHHmmss") + UserOperateContext.Current.Session_UsrInfo.ID;    //生成入库编码
            delivery.ConsigneeID = ConsigneeID;
            delivery.DeliveryType = "MatertalOutType-1";
            delivery.OperationTime = DateTime.Now;//操作时间--20151126调换与出库时间位置
            delivery.OperatorCode = UserOperateContext.Current.Session_UsrInfo.ID;
            delivery.DeliveryTime = DeliveryDate;//出库时间
            delivery.ReceivingStoreID = ReceivingStoreID;
            delivery.Remark = Remark;
            delivery.AmbulanceCode = AmbulanceCode == "" ? null : AmbulanceCode;//20151126--增加车辆编码
            //foreach(I_DeliveryDetail item  in  relist)
            //{
            //     item.TargetUserID = ConsigneeID;
            //}
          


            //delivery.SourceStoreID

            string errorMsg = "";
            if (new I_DeliveryBLL().DeliveryOerate(delivery, relist, ref errorMsg))
                return this.JsonResult(Utility.E_JsonResult.OK, "出库信息成功！", null, null);
            else
                return this.JsonResult(Utility.E_JsonResult.Error, errorMsg, null, null);
        }
    }
}
